<template>
  <view class="leave-home">
    <!-- 顶部导航 -->
    <view class="nav-header">
      <view class="nav-left" @click="goBack">
        <u-icon name="arrow-left" color="#ffffff" size="24"></u-icon>
      </view>
      <view class="nav-center">
        <text class="nav-title">请假报备</text>
      </view>
      <view class="nav-right"> </view>
    </view>

    <!-- 页面内容 -->
    <view class="nav-content">
      <!-- 新建请假申请 -->
      <view class="section create-section">
        <view class="create-card" @click="handleCreate">
          <view class="create-icon" :style="{ background: createAction.bgColor }">
            <u-icon :name="createAction.icon" color="#fff" size="32"></u-icon>
          </view>
          <view class="create-info">
            <text class="create-title">{{ createAction.title }}</text>
            <text class="create-desc">{{ createAction.desc }}</text>
          </view>
        </view>
      </view>

      <!-- 功能模块 -->
      <view class="section">
        <view class="section-header">
          <text class="section-title">功能模块</text>
          <text class="section-tip">常用请假流程入口</text>
        </view>
        <view class="quick-actions">
          <view
            class="action-card"
            v-for="action in quickActions"
            :key="action.id"
            @click="handleAction(action)"
          >
            <view class="action-icon" :style="{ background: action.bgColor }">
              <u-icon :name="action.icon" color="#fff" size="28"></u-icon>
            </view>
            <view class="action-info">
              <text class="action-title">{{ action.title }}</text>
              <text class="action-desc">{{ action.desc }}</text>
            </view>
            <u-icon name="arrow-right" color="#c0c4cc" size="18" />
          </view>
        </view>
      </view>

      <!-- 审批中的请假报备 -->
      <view class="section">
        <view class="section-header">
          <text class="section-title">我的请假-进行中</text>
        </view>
        <view v-if="loadingCurrent" class="loading-box">
          <u-loading-icon size="24" text="加载中..." />
        </view>
        <view
          v-else-if="currentApplications && currentApplications.length > 0"
          class="current-applications"
        >
          <view
            v-for="application in currentApplications"
            :key="application.id"
            class="application-card"
            @click="handleViewApplication(application)"
          >
            <view class="card-header">
              <view class="title-block">
                <text class="title">{{ application.reason || '未填写事由' }}</text>
              </view>
              <u-tag
                :text="getStatusLabel(application.currentStatus)"
                :type="getStatusTagType(application.currentStatus)"
                size="mini"
                plain
              />
            </view>

            <view class="card-body">
              <view class="info-row" v-if="application.location">
                <text class="info-label">地点</text>
                <text class="info-value">{{ application.location }}</text>
              </view>
              <view class="info-row">
                <text class="info-label">时段</text>
                <text class="info-value">
                  {{ formatDateRange(application.startTime, application.endTime) }}
                </text>
              </view>
              <!-- <view class="info-row">
                <text class="info-label">天数</text>
                <text class="info-value">{{ application.totalDays ?? '-' }} 天</text>
              </view> -->
              <view class="info-row">
                <text class="info-label">当前步骤</text>
                <text class="info-value">{{ application.currentStep || '待发起' }}</text>
              </view>
              <view class="info-row" v-if="application.currentApproverName">
                <text class="info-label">当前处理人</text>
                <text class="info-value">{{ application.currentApproverName }}</text>
              </view>
            </view>

            <view class="card-footer">
              <text class="footer-text">点击查看详情</text>
              <u-icon name="arrow-right" color="#909399" size="16" />
            </view>
          </view>
        </view>
        <view v-else class="empty-box">
          <u-empty mode="list" text="暂无审批中的请假申请" />
        </view>
      </view>
    </view>
  </view>
  <!-- 模板选择弹窗 -->
  <u-popup
    :show="templatePopupVisible"
    mode="center"
    borderRadius="16"
    @close="templatePopupVisible = false"
  >
    <view class="template-popup">
      <view class="popup-title">选择报备类型</view>
      <view class="template-grid">
        <view
          v-for="template in templateOptions"
          :key="template.id"
          class="template-card"
          @click="handleSelectTemplate(template)"
        >
          <text class="template-name">{{ template.templateName }}</text>
          <text class="template-desc">{{ template.description || '点击选择此类型' }}</text>
        </view>
      </view>
      <u-button size="small" text="取消" @click="templatePopupVisible = false" />
    </view>
  </u-popup>
</template>

<script setup lang="ts">
import { computed, ref, onMounted } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { UserManager } from '@/utils/user'
import {
  getCurrentInProgressApplication,
  getEnabledLeaveTemplates,
  type LeaveApplicationDetail,
  type LeaveTemplateSimple,
} from '@/Api/leave'

const userInfo = computed(() => UserManager.getFullUserInfo() || { name: '员工' })
const currentApplications = ref<LeaveApplicationDetail[]>([])
const templateOptions = ref<LeaveTemplateSimple[]>([])
const templatePopupVisible = ref(false)
const isFirstLoad = ref(true)
const loadingCurrent = ref(false)
// 新建请假申请配置
const createAction = ref({
  title: '新建请假报备',
  desc: '创建新的请假报备申请',
  icon: 'plus-circle',
  bgColor: 'linear-gradient(135deg, #6fe7dd 0%, #3490de 100%)',
})

// 功能模块
const quickActions = ref([
  {
    id: 1,
    title: '我的请假',
    desc: '请假/外出报备',
    icon: 'calendar',
    bgColor: 'linear-gradient(135deg, #a8edea 0%, #fed6e3 100%)',
    path: '/pages/leave/applications/index',
  },
  {
    id: 2,
    title: '待我审批',
    desc: '待我审批的请假报备',
    icon: 'file-text',
    bgColor: 'linear-gradient(135deg, #f6d365 0%, #fda085 100%)',
    path: '/pages/leave/approvals/pending',
  },
  {
    id: 3,
    title: '我的审批',
    desc: '查看我已审批的请假报备',
    icon: 'list',
    bgColor: 'linear-gradient(135deg, #a18cd1 0%, #fbc2eb 100%)',
    path: '/pages/leave/approvals/history',
  },
])

// 返回上一页
const goBack = () => {
  const pages = getCurrentPages()
  // 如果页面栈只有1个页面，说明无法返回，直接跳转到首页
  if (pages.length <= 1) {
    uni.reLaunch({
      url: '/pages/index/index',
    })
  } else {
    // 有多个页面，执行返回操作
    uni.navigateBack({
      delta: 1,
    })
  }
}

// 创建请假申请
const handleCreate = async () => {
  if (!templateOptions.value.length) {
    await loadTemplateOptions()
  }

  if (!templateOptions.value.length) {
    uni.showToast({ title: '暂无可用模板', icon: 'none' })
    return
  }

  // 根据用户的 externalLiaison 字段自动选择模板
  const userInfo = UserManager.getFullUserInfo()
  const externalFlag = Number(userInfo?.externalLiaison ?? 0)
  const isExternalUser = externalFlag === 1

  // 查找适合当前用户的模板
  const findTemplateForUser = (isExternal: boolean) => {
    // 1. 优先根据 templateCode 查找
    const preferredCode = isExternal ? 'leave_report' : 'outing_report'

    const preferredTemplate = templateOptions.value.find(
      (item) => (item as any).templateCode === preferredCode,
    )
    if (preferredTemplate) {
      return preferredTemplate
    }

    // 2. 根据关键词查找
    const keywords = isExternal
      ? ['外出', '外部', '对外', '单位']
      : ['内部', '报备', '卫健委', '人员']

    const keywordTemplate = templateOptions.value.find((item) => {
      const name = item.templateName || ''
      const description = item.description || ''
      return keywords.some((keyword) => name.includes(keyword) || description.includes(keyword))
    })
    if (keywordTemplate) {
      return keywordTemplate
    }

    // 3. 返回第一个模板
    return templateOptions.value[0]
  }

  const targetTemplate = findTemplateForUser(isExternalUser)

  // 如果只有一个模板，直接打开
  if (templateOptions.value.length === 1) {
    handleSelectTemplate(targetTemplate)
    return
  }

  // 如果找到了匹配的模板，直接打开
  if (targetTemplate) {
    handleSelectTemplate(targetTemplate)
    return
  }

  // 否则显示选择弹窗
  templatePopupVisible.value = true
}

// 加载模板选项
const loadTemplateOptions = async () => {
  try {
    const res: any = await getEnabledLeaveTemplates()
    const body = res?.data || res
    templateOptions.value = body?.data || body || []
  } catch (error) {
    console.error('加载模板列表失败:', error)
  }
}

// 加载当前进行中的请假申请
const loadCurrentApplication = async () => {
  try {
    loadingCurrent.value = true
    const userInfo = UserManager.getFullUserInfo()
    if (!userInfo?.id) {
      console.warn('[loadCurrentApplication] 用户信息不存在')
      currentApplications.value = []
      return
    }

    const res: any = await getCurrentInProgressApplication(Number(userInfo.id))

    // 处理返回的数据结构
    // 根据响应拦截器，res 可能是 { code: 200, message: "...", data: [...] }
    // 或者直接是 { code: 200, data: [...] }
    let dataArray: any[] | null = null

    if (res?.code === 200 && res?.data) {
      // 标准格式：{ code: 200, data: [...] }
      if (Array.isArray(res.data)) {
        dataArray = res.data
      } else if (res.data?.data && Array.isArray(res.data.data)) {
        // 嵌套格式：{ code: 200, data: { data: [...] } }
        dataArray = res.data.data
      } else if (res.data && typeof res.data === 'object' && res.data.id) {
        // 单个对象：{ code: 200, data: {...} }，转换为数组
        dataArray = [res.data]
      }
    } else if (Array.isArray(res)) {
      // 直接返回数组
      dataArray = res
    } else if (Array.isArray(res?.data)) {
      // { data: [...] }
      dataArray = res.data
    } else if (res && typeof res === 'object' && res.id) {
      // 直接返回对象，转换为数组
      dataArray = [res]
    }

    // 处理数组情况
    if (dataArray && dataArray.length > 0) {
      // 保留整个数组
      currentApplications.value = dataArray
    } else {
      currentApplications.value = []
    }
  } catch (error) {
    console.error('[loadCurrentApplication] 加载失败:', error)
    currentApplications.value = []
  } finally {
    loadingCurrent.value = false
  }
}

// 格式化日期时间
const formatDate = (value?: string) => {
  if (!value) return '-'
  return value.replace('T', ' ').substring(0, 10)
}

// 格式化日期时间
const formatDateTime = (value?: string) => {
  if (!value) return '-'
  return value.replace('T', ' ').substring(0, 16)
}

// 格式化日期范围
const formatDateRange = (start?: string, end?: string) => {
  if (!start || !end) return '-'
  const startStr = formatDateTime(start)
  const endStr = formatDateTime(end)
  return `${startStr} 至 ${endStr}`
}

// 获取状态标签类型
const getStatusTagType = (status?: string) => {
  const map: Record<string, 'info' | 'warning' | 'success' | 'error'> = {
    draft: 'info',
    pending: 'warning',
    approved: 'success',
    rejected: 'error',
    cancelled: 'info',
  }
  return map[status || ''] || 'info'
}

// 获取状态标签文本
const getStatusLabel = (status?: string) => {
  const map: Record<string, string> = {
    draft: '草稿',
    pending: '审批中',
    approved: '已通过',
    rejected: '已驳回',
    cancelled: '已撤销',
  }
  return map[status || ''] || '未知状态'
}

// 查看请假申请详情
const handleViewApplication = (application: LeaveApplicationDetail) => {
  if (!application?.id) return
  openFormPage({
    templateId: application.flowTemplateId,
    templateName: application.flowTemplateName,
    leaveId: application.id,
    templateCode:
      (application as any)?.flowTemplateCode || inferTemplateCode(application.flowTemplateName),
    mode: 'view',
  })
}

// 选择模板
const handleSelectTemplate = (template: LeaveTemplateSimple) => {
  templatePopupVisible.value = false
  openFormPage({
    templateId: template.id,
    templateCode: (template as any).templateCode || inferTemplateCode(template.templateName),
    templateName: template.templateName,
    mode: 'create',
  })
}

// 打开表单页面
const openFormPage = (params: Record<string, any>) => {
  const query = buildQueryString(params)
  uni.navigateTo({
    url: `/pages/leave/forms/index${query ? `?${query}` : ''}`,
  })
}

// 构建查询字符串
const buildQueryString = (params: Record<string, any>) => {
  return Object.entries(params)
    .filter(([, value]) => value !== undefined && value !== null && value !== '')
    .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`)
    .join('&')
}

// 推断模板代码
const inferTemplateCode = (name?: string, fallback?: string) => {
  if (fallback) return fallback
  if (!name) return 'leave_report'
  if (name.includes('外出') || name.includes('报备')) return 'outing_report'
  return 'leave_report'
}

// 处理功能模块点击
const handleAction = (action: (typeof quickActions.value)[number]) => {
  if (!action.path) {
    uni.showToast({ title: '功能建设中', icon: 'none' })
    return
  }
  uni.navigateTo({
    url: action.path,
    fail: () => uni.showToast({ title: '页面开发中', icon: 'none' }),
  })
}

// 页面挂载时加载数据
onMounted(async () => {
  await loadTemplateOptions()
  await loadCurrentApplication()
})

// 页面显示时加载数据
onShow(() => {
  if (isFirstLoad.value) {
    isFirstLoad.value = false
    return
  }
  // 页面显示时重新加载当前进行中的申请
  loadCurrentApplication()
})
</script>

<style scoped lang="scss">
.leave-home {
  position: relative;
  height: 100vh;
  background: #f7f8fa;
  box-sizing: border-box;
  overflow: hidden;
  display: flex;
  flex-direction: column;

  &::before {
    content: '';
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    height: 260rpx;
    background: linear-gradient(135deg, #6366f1 0%, #818cf8 50%, #a5b4fc 100%);
    z-index: 0;
    border-radius: 0 0 60rpx 60rpx;
  }

  /* 顶部导航 */
  .nav-header {
    // background: linear-gradient(135deg, #1a3582 0%, #1890ff 100%);
    padding: 46px 32rpx 20rpx 32rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    color: white;
    // position: fixed;
    // top: 0;
    // left: 0;
    // right: 0;
    z-index: 99;

    .nav-left {
      width: 60rpx;
      height: 60rpx;
      display: flex;
      align-items: center;
      justify-content: center;

      .back-icon {
        font-size: 40rpx;
        font-weight: bold;
      }
    }

    .nav-center {
      flex: 1;
      text-align: center;

      .nav-title {
        font-size: 36rpx;
        font-weight: bold;
      }
    }

    .nav-right {
      min-width: 22px;
      .save-btn {
        font-size: 28rpx;
        padding: 12rpx 24rpx;
        background: rgba(255, 255, 255, 0.2);
        border-radius: 12rpx;
      }
    }
  }

  .nav-content {
    flex: 1;
    overflow: auto;
    padding: 32rpx;
  }

  .section {
    margin-top: 48rpx;
    background: #fff;
    border-radius: 24rpx;
    padding: 28rpx;
    position: relative;
    z-index: 1;
    box-shadow: 0 12rpx 32rpx rgba(30, 60, 130, 0.08);

    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .section-title {
        font-size: 30rpx;
        font-weight: 600;
        color: #303133;
      }

      .section-tip {
        font-size: 24rpx;
        color: #a0a4ab;
      }
    }

    .quick-actions {
      display: flex;
      flex-direction: column;

      .action-card {
        display: flex;
        align-items: center;
        margin-top: 20rpx;

        .action-icon {
          width: 96rpx;
          height: 96rpx;
          border-radius: 24rpx;
          display: flex;
          align-items: center;
          justify-content: center;
        }

        .action-info {
          flex: 1;
          margin: 0 24rpx;
          display: flex;
          flex-direction: column;

          .action-title {
            font-size: 30rpx;
            font-weight: 600;
            color: #303133;
          }

          .action-desc {
            font-size: 24rpx;
            color: #909399;
          }
        }
      }
    }

    .timeline {
      position: relative;
      padding-left: 24rpx;
      display: flex;
      flex-direction: column;
      gap: 24rpx;

      &::before {
        content: '';
        position: absolute;
        left: 10rpx;
        top: 8rpx;
        bottom: 8rpx;
        width: 2rpx;
        background: #e4e7ed;
      }

      .timeline-item {
        display: flex;
        gap: 16rpx;

        .dot {
          width: 20rpx;
          height: 20rpx;
          border-radius: 50%;
          background: #2979ff;
          margin-top: 10rpx;
        }

        .content {
          flex: 1;

          .content-header {
            display: flex;
            align-items: center;
            gap: 16rpx;

            .record-type {
              font-size: 28rpx;
              color: #303133;
              font-weight: 600;
            }
          }

          .record-time {
            font-size: 24rpx;
            color: #909399;
            margin-top: 6rpx;
          }

          .record-desc {
            font-size: 24rpx;
            color: #a0a4ab;
            margin-top: 4rpx;
          }
        }
      }
    }

    .loading-box {
      padding: 40rpx 0;
      display: flex;
      justify-content: center;
      align-items: center;
    }

    .current-applications {
      margin-top: 20rpx;
      display: flex;
      flex-direction: column;
      gap: 20rpx;

      .application-card {
        background: #f9fbff;
        border: 1rpx solid #e4e7ed;
        border-radius: 16rpx;
        padding: 24rpx;
        transition: all 0.2s;

        &:active {
          transform: scale(0.98);
          box-shadow: 0 4rpx 12rpx rgba(30, 60, 130, 0.1);
        }

        .card-header {
          display: flex;
          justify-content: space-between;
          align-items: flex-start;
          margin-bottom: 20rpx;

          .title-block {
            flex: 1;
            min-width: 0;

            .title {
              display: block;
              font-size: 30rpx;
              font-weight: 600;
              color: #303133;
              margin-bottom: 8rpx;
            }

            .subtitle {
              display: block;
              font-size: 24rpx;
              color: #909399;
            }
          }
        }

        .card-body {
          .info-row {
            display: flex;
            margin-bottom: 12rpx;
            font-size: 26rpx;

            .info-label {
              width: 140rpx;
              color: #909399;
              flex-shrink: 0;
            }

            .info-value {
              flex: 1;
              color: #303133;
              word-break: break-all;
            }
          }
        }

        .card-footer {
          margin-top: 20rpx;
          padding-top: 20rpx;
          border-top: 1rpx solid #e4e7ed;
          display: flex;
          justify-content: space-between;
          align-items: center;

          .footer-text {
            font-size: 24rpx;
            color: #909399;
          }
        }
      }
    }

    .empty-box {
      padding: 40rpx 0;
    }
  }

  .create-section {
    padding: 0;
    background: transparent;
    box-shadow: none;
    margin-top: 0;

    .create-card {
      background: #fff;
      border-radius: 24rpx;
      padding: 32rpx;
      display: flex;
      flex-direction: column;
      align-items: center;
      box-shadow: 0 12rpx 32rpx rgba(30, 60, 130, 0.08);
      transition: transform 0.2s, box-shadow 0.2s;

      &:active {
        transform: scale(0.98);
        box-shadow: 0 8rpx 24rpx rgba(30, 60, 130, 0.12);
      }

      .create-icon {
        width: 112rpx;
        height: 112rpx;
        border-radius: 28rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        flex-shrink: 0;
        margin-bottom: 8rpx;
      }

      .create-info {
        flex: 1;
        min-width: 0;
        margin: 0 24rpx;

        .create-title {
          display: block;
          font-size: 34rpx;
          font-weight: 700;
          color: #303133;
          margin-bottom: 8rpx;
          display: flex;
          align-items: center;
          justify-content: center;
        }

        .create-desc {
          display: block;
          font-size: 26rpx;
          color: #909399;
        }
      }
    }
  }
}

.template-popup {
  width: 640rpx;
  padding: 32rpx;
  text-align: center;

  .popup-title {
    font-size: 32rpx;
    font-weight: 600;
    margin-bottom: 24rpx;
  }

  .template-grid {
    display: flex;
    flex-direction: column;
    gap: 16rpx;
    margin-bottom: 16rpx;
  }

  .template-card {
    border: 1rpx solid #e4e7ed;
    border-radius: 16rpx;
    padding: 20rpx;
    text-align: left;
    background: #f9fbff;

    .template-name {
      font-size: 28rpx;
      font-weight: 600;
      color: #303133;
    }

    .template-desc {
      display: block;
      margin-top: 8rpx;
      font-size: 24rpx;
      color: #909399;
    }
  }
}
</style>
